package com.sanpu.kxe.business.member.presenter;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.sanpu.kxe.R;
import com.sanpu.kxe.base.KxeApplication;
import com.sanpu.kxe.business.main.bean.UserCenterOutput;
import com.sanpu.kxe.business.main.view.MainActivity;
import com.sanpu.kxe.business.member.bean.MemberPayTypeOutput;
import com.sanpu.kxe.business.member.contract.MemberCashierContract;
import com.sanpu.kxe.business.member.model.MemberModel;
import com.sanpu.kxe.business.trade.bean.PayOrderOutput;
import com.sanpu.kxe.business.trade.provider.ITradeProvider;
import com.sanpu.kxe.common.cache.CacheManage;
import com.sanpu.kxe.common.cache.CacheModel;
import com.sanpu.kxe.common.enums.PayType;
import com.sanpu.kxe.common.interfaces.CommonConfig;
import com.sanpu.kxe.jump.eventbus.RefreshBalanceEvent;
import com.sanpu.kxe.jump.paysdk.AliPayUtil;
import com.sanpu.kxe.jump.paysdk.PayResult;
import com.sanpu.kxe.jump.paysdk.WXPayUtil;
import com.sanpu.kxe.module.dialog.GlobalDialog;
import com.sanpu.kxe.utils.AppContextUtil;
import com.sanpu.kxe.utils.PublicProviderUtil;
import com.sanpu.kxe.utils.ToastUtil;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.EventBus;

import java.util.List;
import java.util.Map;

import rx.Observer;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

/**
 * Description：新版会员充值支付页
 * Created by 薛勇军 on 2019/3/19.
 */

public class MemberCashierPresenter implements MemberCashierContract.Presenter {

    private MemberCashierContract.View mView;

    private CompositeSubscription mSubscription;

    private String mVipOpenId, mRealPrice;

    public MemberCashierPresenter(MemberCashierContract.View mView, String vipOpenId, String realPrice) {
        this.mView = mView;
        this.mVipOpenId = vipOpenId;
        this.mRealPrice = realPrice;
        mSubscription = new CompositeSubscription();

        KxeApplication.msgApi = WXAPIFactory.createWXAPI(mView.getContext(), null);
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(CommonConfig.WX_PAY_RESULT_ACTION);
        ((Activity) mView.getContext()).registerReceiver(wxPayReceiver, intentFilter);
    }

    @Override
    public void upgradeVipTypeList() {
        mView.showLoadingDialog(true);
        Subscription subscription = MemberModel.getInstance().upgradeVipTypeList()
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<List<MemberPayTypeOutput>>() {
                    @Override
                    public void onCompleted() {
                        mView.dismissLoadingDialog();
                    }

                    @Override
                    public void onError(Throwable e) {
                        mView.dismissLoadingDialog();
                        mView.showErrorText(e);
                    }

                    @Override
                    public void onNext(List<MemberPayTypeOutput> memberPayTypeOutputs) {
                        mView.showDataListView(memberPayTypeOutputs);
                    }
                });
        mSubscription.add(subscription);
    }

    @Override
    public void onPayClickListener(MemberPayTypeOutput payTypeOutput) {
        if (payTypeOutput != null) {
            switch (payTypeOutput.getBusinessType()) {
                case CommonConfig.PAYTYPE_BALANCE:
                    mView.onShowPasswordPopup();
                    break;
                case CommonConfig.PAYTYPE_UNIONPAY_SCAN:
                    openPaymentQRcodeActivity(payTypeOutput.getBusinessType(), payTypeOutput.getAppCnlConfId());
                    break;
                case CommonConfig.PAYTYPE_ALIPAY_APP:
                    payOrder(payTypeOutput.getBusinessType(), payTypeOutput.getAppCnlConfId());
                    break;
                case CommonConfig.PAYTYPE_WECHAT_APP:
                    if (!isWXAppInstalledAndSupported()) {
                        ToastUtil.showTextViewPrompt("未安装微信");
                        return;
                    }
                    payOrder(payTypeOutput.getBusinessType(), payTypeOutput.getAppCnlConfId());
                    break;
            }
        }
    }

    @Override
    public void upgradeWithAmt(String payPassword) {
        String mAccountName = "";
        UserCenterOutput centerOutput = CacheManage.getInstance().getCache(CacheModel.USER_CENTER_KEY);
        if (centerOutput != null) {
            mAccountName = centerOutput.getUserName();
        }
        mView.showLoadingDialog(true, "下单中...");
        Subscription subscription = MemberModel.getInstance().balanceUpgradeVip(mRealPrice, mVipOpenId, payPassword, mAccountName)
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        mView.dismissLoadingDialog();
                        mView.showErrorText(e);
                    }

                    @Override
                    public void onNext(String s) {
                        mView.dismissLoadingDialog();
                        EventBus.getDefault().post(new RefreshBalanceEvent());
                        showSuccessDialog();
                    }
                });
        mSubscription.add(subscription);
    }

    /**
     * 支付扫码
     */
    private void openPaymentQRcodeActivity(String busniessType, String appCnlConfId) {
        PayType payType = null;
        try {
            payType = PayType.valueOf(busniessType);
        } catch (Exception e) {
            e.printStackTrace();
        }
        ITradeProvider provider = PublicProviderUtil.getProvider(ITradeProvider.class);
        if (provider != null) {
            provider.openPaymentQRcodeActivity(mView.getContext(), mVipOpenId, payType, mRealPrice, appCnlConfId);
        }
    }

    /**
     * 统一下单接口
     */
    private void payOrder(final String busniessType, String appCnlConfId) {
        mView.showLoadingDialog(true, "下单中...");
        ITradeProvider tradeProvider = PublicProviderUtil.getProvider(ITradeProvider.class);
        if (tradeProvider != null) {
            Subscription subscription = tradeProvider.payOrder(mRealPrice, appCnlConfId, mVipOpenId)
                    .subscribeOn(Schedulers.io())
                    .unsubscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Observer<PayOrderOutput>() {
                        @Override
                        public void onCompleted() {
                            mView.dismissLoadingDialog();
                        }

                        @Override
                        public void onError(Throwable e) {
                            mView.dismissLoadingDialog();
                            mView.showErrorText(e);
                        }

                        @Override
                        public void onNext(PayOrderOutput orderOutput) {
                            if (orderOutput == null) return;
                            switch (busniessType) {
                                case CommonConfig.PAYTYPE_ALIPAY_APP:
                                    AliPayUtil.toPay(mView.getContext(), mHandler, orderOutput.getAttach());
                                    break;
                                case CommonConfig.PAYTYPE_WECHAT_APP:
                                    Map<String, Object> retDatMap = null;
                                    if (!TextUtils.isEmpty(orderOutput.getAttach())) {
                                        retDatMap = new Gson().fromJson(orderOutput.getAttach(),
                                                new TypeToken<Map>() {
                                                }.getType());
                                    }
                                    WXPayUtil.toPay(retDatMap);
                                    break;
                            }
                        }
                    });
            mSubscription.add(subscription);
        }
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case AliPayUtil.SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        showSuccessDialog();
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        showFailDialog();
                    }
                    break;
                }
                default:
                    break;
            }
        }
    };

    /**
     * 本机是否支持微信支付
     */
    public boolean isWXAppInstalledAndSupported() {
        KxeApplication.msgApi.registerApp(CommonConfig.WX_APPID);

        boolean sIsWXAppInstalledAndSupported = KxeApplication.msgApi.isWXAppInstalled()
                && KxeApplication.msgApi.isWXAppSupportAPI();

        return sIsWXAppInstalledAndSupported;
    }

    /**
     * 微信支付的广播接受者
     */
    private BroadcastReceiver wxPayReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent == null) {
                return;
            }
            if (CommonConfig.WX_PAY_RESULT_ACTION.equals(intent.getAction())) {
                // 0 成功 展示成功页面
                // -1 错误 可能的原因：签名错误、未注册APPID、项目设置APPID不正确、注册的APPID与设置的不匹配、其他异常等。
                // -2 用户取消 无需处理。发生场景：用户不支付了，点击取消，返回APP。
                String wxPayCode = intent.getStringExtra(CommonConfig.WX_PAY_RESULT);
                switch (wxPayCode) {
                    case "0":
                        showSuccessDialog();
                        break;
                    case "-1":
                    case "-2":
                        showFailDialog();
                        break;
                    default:
                        break;
                }
            }
        }
    };

    /**
     * 支付成功弹框
     */
    private void showSuccessDialog() {
//        GlobalDialog dialog = new GlobalDialog(mView.getContext())
//                .content("支付成功")
//                .headerIcon(R.drawable.img_dialog_head);
//        dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
//            @Override
//            public void onDismiss(DialogInterface dialog) {
//                AppContextUtil.finishAllExclByActivity(MainActivity.class.getName());
//            }
//        });
//        dialog.show();
        ToastUtil.show("支付成功");
        AppContextUtil.finishAllExclByActivity(MainActivity.class.getName());
    }

    /**
     * 支付失败弹框
     */
    private void showFailDialog() {
        GlobalDialog dialog = new GlobalDialog(mView.getContext())
                .content("支付失败")
                .headerIcon(R.drawable.img_fail_result);
        dialog.show();
    }

    @Override
    public void onDestroyPresenter() {
        if (wxPayReceiver != null) {
            ((Activity)mView.getContext()).unregisterReceiver(wxPayReceiver);
        }
        if (mSubscription != null && !mSubscription.isUnsubscribed()) {
            mSubscription.unsubscribe();
            mSubscription = null;
        }
        if (mView != null) {
            mView = null;
        }
    }
}
